package com.moonbird.springboot.Utils.Qwen;

import com.alibaba.dashscope.audio.asr.transcription.*;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AudioTranscriptionUtil {

  private static final String MODEL = "paraformer-v2";
  private static final String API_KEY = "sk-c91bee81e9ef4fd4abe43a61b8f38479";

  /**
   * 尝试转写上传的音频文件，并返回转写结果。
   *
   * @param audioFile 上传的音频文件
   * @return 转写结果的文本
   */
  public static String transcribeAudio(MultipartFile audioFile) throws IOException {
    // 临时文件路径
    Path tempFilePath = null;
    try {
      // 保存音频文件到临时位置
      tempFilePath = Files.createTempFile("temp_audio", ".wav");
      Files.copy(audioFile.getInputStream(), tempFilePath, StandardCopyOption.REPLACE_EXISTING);

      // 验证音频文件格式
      if (!isValidAudioFile(tempFilePath)) {
        return "Invalid audio format.";
      }

      // 转写音频
      return transcribe(tempFilePath.toString());
    } catch (IOException e) {
      return "Error processing the audio file: " + e.getMessage();
    } finally {
      // 清理临时文件
      if (tempFilePath != null) {
        Files.deleteIfExists(tempFilePath);
      }
    }
  }

  /**
   * 验证文件是否为有效的音频格式。
   *
   * @param filePath 文件路径
   * @return 是否有效
   */
  private static boolean isValidAudioFile(Path filePath) {
    try (InputStream inputStream = Files.newInputStream(filePath)) {
      String mimeType = Files.probeContentType(filePath);
      List<String> validAudioTypes = Arrays.asList("audio/wav", "audio/x-wav", "audio/mpeg", "audio/aac", "audio/flac");
      return validAudioTypes.contains(mimeType);
    } catch (IOException e) {
      return false;
    }
  }

  /**
   * 使用DashScope API进行音频转写。
   *
   * @param filePath 音频文件路径
   * @return 转写结果的文本
   */
  private static String transcribe(String filePath) {
    TranscriptionParam param =
        TranscriptionParam.builder()
            .apiKey(API_KEY)
            .model(MODEL)
            .fileUrls(Collections.singletonList(filePath))
            .parameter("language_hints", new String[]{"zh", "en"})
            .build();

    try {
      Transcription transcription = new Transcription();
      TranscriptionResult result = transcription.asyncCall(param);
      result =
          transcription.wait(
              TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));

      List<TranscriptionTaskResult> taskResultList = result.getResults();
      if (taskResultList != null && !taskResultList.isEmpty()) {
        TranscriptionTaskResult taskResult = taskResultList.get(0);
        String transcriptionUrl = taskResult.getTranscriptionUrl();
        HttpURLConnection connection = (HttpURLConnection) new URL(transcriptionUrl).openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
        JsonArray transcriptsArray = jsonObject.getAsJsonArray("transcripts");
        for (JsonElement transcriptElement : transcriptsArray) {
          JsonObject transcriptObject = transcriptElement.getAsJsonObject();
          JsonArray sentencesArray = transcriptObject.getAsJsonArray("sentences");
          for (JsonElement sentenceElement : sentencesArray) {
            JsonObject sentenceObject = sentenceElement.getAsJsonObject();
            return sentenceObject.get("text").getAsString();
          }
        }
      }
    } catch (Exception e) {
      return "Error transcribing the audio file: " + e.getMessage();
    }
    return "No transcription result found.";
  }
}